package com.xinluxinli.caiwu.service;

import com.xinluxinli.caiwu.entity.EmployeeInfo;
import com.xinluxinli.caiwu.entity.User;
import com.xinluxinli.caiwu.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public boolean loginCheck(User user) {
        if (Objects.isNull(user) && StringUtils.isEmpty(user.getPassword())) {
            return false;
        }
        User userDb = userMapper.selectByUserName(user.getUsername());
        if (Objects.nonNull(userDb) && userDb.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))) {
            return true;
        }
        return false;
    }

    public boolean addUser(User user) {
        if (Objects.isNull(user) && StringUtils.isEmpty(user.getPassword())) {
            return false;
        }

        User userDb = userMapper.selectByUserName(user.getUsername());

        if (Objects.nonNull(userDb)) {
            return false;
        } else {
            String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            User userCreat = new User();
            userCreat.setPassword(md5Password);
            userCreat.setUsername(user.getUsername());
            userCreat.setCtime(new Date());
            userMapper.insert(userCreat);
            return true;
        }
    }

    public boolean cookieLoginCheck(HttpServletRequest request) {
        String username = null;
        String password = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("username".equalsIgnoreCase(cookie.getName())){
                username =cookie.getValue();
            }else if ("password".equalsIgnoreCase(cookie.getName())){
                password=cookie.getValue();
            }
        }

        if (StringUtils.isEmpty(username)&&StringUtils.isEmpty(password)){
            return false;
        }
        User userDb = userMapper.selectByUserName(username);

        if (password.equalsIgnoreCase(userDb.getPassword())){
            return true;
        }
        return false;
    }


}
